﻿using UnityEngine;
using System.Collections;

public class leverScript : MonoBehaviour {
	
	public blockScript partner;
	public bool activated;
	public Texture2D[] textures;
	playerScript player;
	bool isPlayerIn;
	Vector3 startPosition;
	public AudioClip openLeverS;
	
	public interactButton IBut;
	// Use this for initialization
	void Start () {
		isPlayerIn = false;
		try
		{
			GameObject.FindGameObjectWithTag("SoundManager").GetComponent<SoundManagerScript>().audios.Add(this.GetComponent<AudioSource>());
			IBut = GameObject.FindGameObjectWithTag("InteractButton").GetComponent<interactButton>();
		}
		catch
		{
			;
		}
	}
	
	// Update is called once per frame
	void Update () {
		//if(activated)
		//{

		//}
	}
	
	bool playedSound = false;
	void LateUpdate()
	{
		if(!activated)
		{
			if(isPlayerIn && player.isGrounded)
			{
				IBut.canDisplay();
				if(Input.GetKeyDown(KeyCode.F))
				{
					if(player.latestObject != this && !player.havePickUpThisTurn)
					{
						if(!player.havePickUpThisTurn && !player.isCarrying)
						{
							if(!partner.isMoving)
							{
								player.pushLever(this);
								player.havePickUpThisTurn = true;
								networkView.RPC("activate",RPCMode.All);
							}
						}
					}
				}
			}
		}
		else
		{
			if(player != null)
			{
				if(player.isPushingLever)	
				{
					Vector3 inPos = player.getSpriteInatePos();
					Vector3 tmpPos = startPosition;
					tmpPos.z += inPos.z;
					transform.position = tmpPos;
					if(!playedSound)
						if(inPos.x == 1)
						{
							audio.PlayOneShot(openLeverS);
							playedSound = true;
						}
					renderer.material.mainTexture = textures[(int)inPos.x];	
				}
			}
		}
		
		
	}
	
	void OnTriggerEnter(Collider myCol)
	{	
		if(!activated && myCol.tag == "Player" && myCol.networkView.isMine)
		{	
			player = myCol.GetComponent<playerScript>();
			isPlayerIn = true;
		}
	}
	
	void OnTriggerExit(Collider myCol)
	{	
		if(!activated && myCol.tag == "Player" && myCol.networkView.isMine)
		{	
			isPlayerIn = false;
		}
	}
	
	[RPC]
	void activate()
	{
		//renderer.material.mainTexture = textures[0];
		startPosition = transform.position;
		partner.isMoving = true;
		activated = true;
		//lerpCounter = 0;
	}
}
